package bj.gui

import scala.swing.event
import event.ButtonClicked
import scala.swing.Frame
import scala.swing.Label
import scala.swing.Swing
import scala.swing.Button
import scala.swing.FlowPanel
import scala.swing.GridPanel
import scala.swing.Component
import javax.swing.SpinnerNumberModel
import javax.swing.JSpinner
import javax.swing.ImageIcon
import javax.swing.event.ChangeListener
import scala.swing.event.ActionEvent
import javax.swing.event.ChangeEvent

class ATM extends Frame {
  javax.swing.UIManager.setLookAndFeel(Constants.LF)
  println("ATM window opened")
  title = "Blackjack - ATM"
  minimumSize = Constants.ATMSize

    val moneySpinner = new JSpinner(new SpinnerNumberModel(100.00, 0.00, 5000.00, 20)) with ChangeListener {
	  addChangeListener(this)
	  def stateChanged(e : ChangeEvent) = {
	    val doubleVal = this.getValue().toString().toDouble
	    val intVal = doubleVal.toInt
	    val roundOff = (intVal/20)*20
	    println("round up: " +roundOff.toDouble)
	    removeChangeListener(this) /* Prevent recursive calls to stateChanged */
	    this.setValue(roundOff.toDouble)
	    addChangeListener(this) /* Listen to events again */
	  }
  }
  moneySpinner.setEditor(new JSpinner.NumberEditor(moneySpinner, "0.00"))
  
  val ATMPanel = new FlowPanel() {
    contents += new Label {
      text = "Money to Withdraw: $"
    }
    contents += Component.wrap(moneySpinner)
    background = Constants.greenBack
  }

  val okButton = new Button { text = "OK" }
  val cancelButton = new Button { text = "Cancel" }
  val buttonPanel = new FlowPanel() {
    contents += okButton
    contents += cancelButton
    background = Constants.greenBack
  }
  contents = new GridPanel(2, 1) {
    contents += new Label {
      icon = new ImageIcon("images/BJLogo2.gif")
    }
    contents += new GridPanel(2, 1) {
      contents += ATMPanel
      contents += buttonPanel
    }
    border = Swing.EmptyBorder(20)
    background = Constants.greenBack
  }
  listenTo(okButton)
  listenTo(cancelButton)
  reactions += {
    case ButtonClicked(`okButton`) =>
      println("Clicked ok button")
      val addS = moneySpinner.getValue().toString()
      val d : Double = addS.toDouble
      Lobby.top.bankrollValue += d
      Lobby.top.bankrollLabel.text = "Bankroll: $" + String.format("%3.2f", double2Double(Lobby.top.bankrollValue))
      // Call method addToBankroll in the Lobby which will cause the House to be informed of the increase in bankroll
      Lobby.top.addToBankroll(d)
      this.close()
    case ButtonClicked(`cancelButton`) =>
      this.close()
  }
  visible = true
}